(function ($) {
  $.fn.max_length = function (settings) {
    var max_length = settings.max_length;
    return this.each(function () {
      var hint_field = $(this).find('.char-hint');
      var input_field = $(this).find('.very-input');
      function update_count() {
        var very_content = (input_field.is("textarea"))? input_field.val(): input_field.text();
        var input_length = very_content.length;
        var diff = max_length - input_length;
        if (diff < 0) {
          // truncate the code
          very_content = very_content.substr(0, max_length);
          if (input_field.is("textarea")) {
            input_field.val(very_content);
          } else {
            input_field.text(very_content);
          }
          diff = 0;
        }
        hint_field.text(sprintf(gettext("%d chars remain"), diff));
      };  
      function limit_check(event) {
        var very_content = (input_field.is("textarea"))? input_field.val(): input_field.text();
        var input_length = very_content.length;
        var diff = max_length - input_length;
        var code = event.keyCode;
        if (diff > 0) {
          return true;
        }
        switch (code) {
          case 8:  // allow delete
          case 9:
          case 17:
          case 36: // and cursor keys
          case 35:
          case 37: 
          case 38:
          case 39:
          case 40:
          case 46:
          case 65:
            return true;
          default:
            return false;
        }
      }
      input_field.keyup(update_count).change(update_count);
      input_field.keydown(limit_check);
      update_count();
    });
  };
})(jQuery);

